import {WX_LOGIN} from "@/api/login";
import {requestPost} from "@/until/means/request";

const getToken = () => {
  return uni.getStorageSync('token')
}

const setToken = (token) => {
  uni.setStorageSync('token', token)
}

const getWxToken = () => {
  return uni.getStorageSync('wxToken')
}

const setWXToken = (token) => {
  uni.setStorageSync('wxToken', token)
}

const checkToken = () => {
  const token = getToken()
  return token != null && token !== ''
}

const loginCheck = () => {
  return new Promise(async (resolve, reject) => {
    if (!checkToken()) {
      const loginSuccessFlag = await login();
      resolve(loginSuccessFlag)
      return
    }
    resolve(true)
  })
}

const login = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      "provider": "weixin",
      "onlyAuthorize": true, // 微信登录仅请求授权认证
      success: function (event) {
        const {code} = event
        setWXToken(code)
        requestPost({url: WX_LOGIN, data: {code}}).then(res => {
          const accessToken = res?.accessToken || 'simulateToken'
          setToken(accessToken)
          resolve(accessToken && accessToken !== '')
        }).catch(err => {
          setWXToken('')
          setToken('')
          resolve(false)
        })
      },
      fail: function (err) {
        setWXToken('')
        setToken('')
        resolve(false)
      }
    })
  })
}

const getQueryHeaders = () => {
  return {
    'X-Access-Token': getToken()
  }
}

export {loginCheck, getQueryHeaders,setToken}
